// 全局导出这个behavior， 或者设置变量名再导出也行
module.exports = Behavior({
  data:{
    //订单主表字段
    mainField:[
      {field_id: 'xiangmu;value',type: 'select',label: '项目',selectType: 'project',required: true},
      {field_id: 'reference1_all_delivery;value',type: 'select',label: '工地',selectType: 'delivery',required: true,disabled:false },
      {field_id: 'Order_client_ID;value',type: 'select',label: '所属单位',selectType: 'client',disabled: false},
      {label: '联系方式',children: [
          {field_id: 'gongdilianxiren',type: 'text',placeholder: '联系人'},
          {field_id: 'gongdilianxidianhua',type: 'text',placeholder: '联系电话'},
        ]},
      {label: '订单名称',field_id: 'order_name',type: 'text',placeholder: '订单名称',required: true},
      /*  {label: '工地价格',required: true,children: [
            {field_id: 'construction_payment',type: 'picker',placeholder: '请选择'},
            {field_id: 'construction_price',type: 'digit',placeholder: '工地价格'},
          ]},*/
      {label: '开始时间',field_id: 'start_time',type: 'calendar',placeholder: '请选择',required: true,disabled: false},
      {label: '结束时间',field_id: 'end_time',type: 'calendar',placeholder: '请选择',required: true,disabled: false},
      {label: '需要运单号',field_id: 'need_fill_order_no',type: 'radio',placeholder: '请选择',radioType: 'need_fill_order_no'},
      {label: '需要运单图片',field_id: 'need_fill_order_img',type: 'radio',placeholder: '请选择',radioType: 'need_fill_order_img'},
      {label: '需要挖机号',field_id: 'need_fill_excavator_no',type: 'radio',placeholder: '请选择',radioType: 'need_fill_excavator_no'},
      {label: '需要挖机图片',field_id: 'need_fill_excavator_img',type: 'radio',placeholder: '请选择',radioType: 'need_fill_excavator_img'},
      // {label: '泥尾需要挖机号',field_id: 'need_fill_excavator_no_end',type: 'radio',placeholder: '请选择',radioType: 'need_fill_excavator_no_end'},
      // {label: '泥尾需要挖机图片',field_id: 'need_fill_excavator_img_end',type: 'radio',placeholder: '请选择',radioType: 'need_fill_excavator_img_end'},
      {label: '需要填写趟次',field_id: 'need_fill_transport_times',type: 'radio',placeholder: '请选择',radioType: 'need_fill_transport_times'},
      {label: '需要填写方数',field_id: 'need_fill_square_number',type: 'radio',placeholder: '请选择',radioType: 'need_fill_square_number'},
      {label: '需要车数控制',field_id: 'need_car_no_control',type: 'radio',placeholder: '请选择',radioType: 'need_car_no_control'},
      {label: '填写车数',field_id: 'fill_car_no',type: 'number',placeholder: '请填写'},

    ],
    // 订单主表需要权限控制字段
    mainAuthField: {
      // ZhiDingXieHuoDiZhi: {label: '指定卸货地址',field_id: 'ZhiDingXieHuoDiZhi',type: 'location',placeholder: '请选择',selectType: 'location'},
      ZhiDingXieHuoDiZhi: {label: '指定卸货地址',field_id: 'ZhiDingXieHuoDiZhi',type: 'text',placeholder: '请填写'},
      ZhiDingXieHuoJingDu: {label: '指定卸货地址经度',field_id: 'ZhiDingXieHuoJingDu',type: 'digit',placeholder: '请填写'},
      ZhiDingXieHuoWeiDu: {label: '指定卸货地址纬度',field_id: 'ZhiDingXieHuoWeiDu',type: 'digit',placeholder: '请填写'},
      ZhiDingXieHuoDiZhiXiaoNaChang: {label: '指定卸货地址消纳场',field_id: 'ZhiDingXieHuoDiZhiXiaoNaChang;value',type: 'select',placeholder: '请选择',selectType: 'destination'},
      YanShiXieHuoFenZhongShu: {label: '延时卸货分钟数',field_id: 'YanShiXieHuoFenZhongShu',type: 'number',placeholder: '请填写'},
      TuZhiWeiZhiLieBiao: {label: '需要填写图纸位置',field_id: 'TuZhiWeiZhiLieBiao',type: 'textarea',placeholder: '多个位置逗号分隔，如：a位置,b位置,c位置'},
    },
    destField:[
      {field_id: 'reference1_all_destination;value',type: 'select',label: '消纳场',selectType: 'destination',required: true},
      {field_id: 'Order_client_ID;value',type: 'select',label: '所属单位',selectType: 'destClient'},
      {label: '联系方式',children: [
          {field_id: 'xiaonachanglianxiren',type: 'text',placeholder: '联系人'},
          {field_id: 'xiaonachanglianxidianhua',type: 'text',placeholder: '联系电话'},
        ]},
      {field_id: 'reference1_goods;value',type: 'select',label: '泥种',selectType: 'goods',required: true},
      {label: '工地价格',required: true,children: [
          {field_id: 'construction_payment',type: 'picker',placeholder: '请选择'},
          {field_id: 'construction_price',type: 'digit',placeholder: '工地价格'},
        ]},
      {label: '消纳场价格',required: true,children: [
          {field_id: 'destination_payment',type: 'picker',placeholder: '请选择'},
          {field_id: 'Order_amount',type: 'digit',placeholder: '消纳场价格'},
        ]},
      {label: '司机价格',required: true,children: [
          {field_id: 'driver_payment',type: 'picker',placeholder: '请选择'},
          {field_id: 'driver_price',type: 'digit',placeholder: '司机价格'},
        ]},
      {label: '额外金额',required: false,children: [
          {field_id: 'extra_payment',type: 'picker',placeholder: '请选择'},
          {field_id: 'extra_price',type: 'digit',placeholder: '额外金额'},
        ]},
      {label: '泥尾需要挖机号',field_id: 'need_fill_excavator_no_end',type: 'radio',placeholder: '请选择',radioType: 'need_fill_excavator_no_end'},
      {label: '泥尾需要挖机图片',field_id: 'need_fill_excavator_img_end',type: 'radio',placeholder: '请选择',radioType: 'need_fill_excavator_img_end'},
      {label: '泥尾需要运单号',field_id: 'need_fill_order_no_end',type: 'radio',placeholder: '请选择',radioType: 'need_fill_order_no_end'},
      {label: '泥尾需要运单图片',field_id: 'need_fill_order_img_end',type: 'radio',placeholder: '请选择',radioType: 'need_fill_order_img_end'},

    ], //消纳场明细表字段

    /*提交数据*/
    formData: {}, //主表数据
    destinationAssign: [],  //泥尾数据
    driverDetail: [], //工地指派司机

    /*弹出层显示标识*/
    showAddDest: false,   //新增泥尾
    showDelivery: false,  //显示工地选择列表
    showDestination: false, //显示消纳场选择列表
    showGoods: false, //显示泥种选择列表
    showDriver: false,  //显示司机选择列表
    showClient: false,  //显示所属单位列表
    showDestClient: false,  //显示泥尾所属单位列表
    showProject: false,   //显示项目列表

    /*弹出层显示内容*/
    deliveryList: [], //工地列表
    destinationList: [], //消纳场列表
    goodsList: [],  //泥种列表
    driverList: [],   //司机列表
    clientList: [],  //所属单位列表
    destClientList: [], //泥尾所属单位列表
    projectList: [],  //项目列表

    /*搜索数据*/
    searchValue: {},

    /*应收应付选择器*/
    showPicker: false,  //显示应收应付选择器
    columns: ['应收','应付'],
    curtPickerField: '',
    curtPickerIndex: 0,
    defaultPickerValue: '',

    /*日历*/
    showCalendar: false,  //显示日历
    defaultDatetimeValue: '',
    resetFlag: false,

    //司机分类选择
    firstActiveIndex: 0,
    secondActiveIndex: 0,
    activeId: [],
    items: [],
    checkAll: false,

    // 231219 yan 车队选择修改为弹出选择器选择
    showDriverPicker: false, //司机车队选择器显示
    carTeamColumns: [
      {values:[],defColumns: 0,}, //一级车队
      {values: [],defColumns: 0,} //二级车队
    ],  //车队选择器选项
    crtDriver: [],  //过滤车队显示的司机
    driverPickerValue: [],  //选择器选择的值
    // 231219 end
    addDestDriver: [],

    fieldNames: {value: 'id',text: 'text',children: 'children'},

    toView: ''
  },
  methods:{

    //获取diy数据
    getCustomData(table_id,where,field_list){
      let url = 'DynamicQuery/query_dynamic_v3',
        post = {limit: 0, page: 1, table_id,oby: `${table_id}.row_id`,field_list};
      where && (post.SearchWhere = {filters: where,type: 'and'});
      return new Promise(resolve => {
        wx.$post(3,url,post).then(res => {
          if (res.errcode != 0) return;
          resolve(res.data.row)
        })
      })
    },
    //获取diy数据（包含明细数据）
    getCustomRow(table_id,row_id){
      return new Promise(resolve => {
        let url = 'DynamicQuery/query_dynamic_v2',
          post = {row_id,table_id}
        wx.$post(3,url,post).then(res => {
          if (res.errcode != 0) return;
          let data = res.data.row && res.data.row[0];

          resolve(data);
        })
      })
    },
    //获取模块字段
    getCustomField(table_id){
      let url = 'QX/PRO_select_field',
        post = {"table": table_id,"fieldname":""};
      return new Promise(resolve => {
        wx.$post(4,url,post).then(res =>{
          if (res.errcode != 0) return;
          let data = res.data.row || [];
          resolve(data);
        })
      })
    },
    //更新自定义数据（包含明细数据）
    updateCustomData(post){
      return new Promise(resolve => {
        let url = 'DynamicUpdate/dynamic_update_v3';
        wx.$post(3,url,post).then(res =>{
          if (res.errcode != 0) return;
          resolve();

        })
      })
    },
    //删除数据
    delData(table_id,data){
      let url = 'DynamicUpdate/dynamic_delete',
        post = {table_id,row_ids: data};
      return new Promise(resolve => {
        wx.$post(3,url,post).then(res => {
          if (res.errcode != 0) return;
          resolve();
        })
      })
    },

    //获取项目
    getProject(){
      return new Promise(resolve => {
        if (this.data.projectList.length){
          resolve(this.data.projectList);
          return
        }
        wx.showLoading({mask: true});
        let fieldList = ['row_id','xiangmumingchen','gongdi','wanglaidanwei']
        let where = [{CompareValue: true, CompareWith: "e_xiangmulixiang.is_used", Operator: "=", or: 0}]
        this.getCustomData('e_xiangmulixiang',where,fieldList.join(',')).then(res => {
          wx.hideLoading();
          let projectList = res || [];
          this.setData({projectList})
          resolve(projectList)
        })
      })

    },
    //获取工地
    getDelivery(){
      return new Promise(resolve => {
        if (this.data.deliveryList.length){
          resolve(this.data.deliveryList)
          return
        }
        let fieldList = ['row_id','delivery_name','lianxiren','lianxidianhua']
        let where = [{CompareValue: true, CompareWith: "all_delivery.is_used", Operator: "=", or: 0}]
        this.getCustomData('all_delivery',where,fieldList.join(',')).then(res => {
          let deliveryList = res || [];
          this.setData({deliveryList});
          resolve(deliveryList);
        })
      })
    },
    //获取消纳场
    getDestination(){
      return new Promise(resolve => {
        if (this.data.destinationList.length){
          resolve(this.data.destinationList)
          return
        }
        let fieldList = ['row_id','destination_name','Order_client_ID','lianxiren','lianxidianhua']
        let where = [{CompareValue: true, CompareWith: "all_destination.is_used", Operator: "=", or: 0}]
        this.getCustomData('all_destination',where,fieldList.join(',')).then(res => {
          let destinationList = res || [];
          this.setData({destinationList})
          resolve(destinationList);
        })
      })
    },
    //获取泥种
    getGoods(){
      return new Promise(resolve => {
        if (this.data.goodsList.length){
          resolve(this.data.goodsList)
          return
        }
        let fieldList = ['row_id','goods_name']
        this.getCustomData('goods','',fieldList.join(',')).then(res => {
          let goodsList = res || [];
          this.setData({goodsList});
          resolve(goodsList);
        })
      })
    },
    //获取所属单位
    getClient(){
      return new Promise(resolve =>{
        if (this.data.clientList.length){
          resolve(this.data.clientList)
          return
        }
        wx.showLoading({mask: true});
        let fieldList = ['row_id','customer_name']
        let where = [{CompareValue: true, CompareWith: "customer.shiweixiuchang", Operator: "=", or: 0}]
        this.getCustomData('customer',where,fieldList.join(',')).then(res => {
          wx.hideLoading();
          let clientList = res || [];
          this.setData({clientList});
          resolve(clientList)
        })
      })
    },
    //获取泥尾所属单位
    getDestClient(){
      return new Promise(resolve => {
        if (this.data.destClientList.length) {
          resolve(this.data.destClientList)
          return
        }
        wx.showLoading({mask: true});
        let fieldList = ['row_id','customer_name']
        let where = [{CompareValue: true, CompareWith: "customer.gongyingshangdanwei", Operator: "=", or: 0}]
        this.getCustomData('customer',where,fieldList.join(',')).then(res => {
          wx.hideLoading();
          let destClientList = res || [];
          destClientList = destClientList.map(({row_id,customer_name}) => ({row_id,customer_name}));
          this.setData({destClientList});
          resolve(destClientList)
        })
      })
    },
    //获取司机
    getDriver(){
      return new Promise(resolve => {
        if (this.data.driverList.length){
          resolve(this.data.driverList)
          return
        }
        this.getCustomData('e_sijiziliaobiao').then(res => {
          let driverList = res || [],
            {driverDetail} = this.data;
          driverList.forEach(item => {
            let {row_id} = item;
            if (driverDetail.some(item => item.reference1_driver == row_id)) {
              item.checked = true;
            }
          })
          this.setData({driverList});
          resolve(driverList);
        })
      })
    },


    //显示应收应付弹窗
    bindShowPicker(e){
      let {field,index} = e.currentTarget.dataset;
      this.data.curtPickerField = field;
      this.data.curtPickerIndex = index;
      // let def = field === 'construction_payment' ?  this.data.formData[field] : this.data.addDestination[field],
      // let def = this.data.addDestination[field],
      let def = this.data.destinationAssign[index][field],
        defIndex = this.data.columns.indexOf(def);
      this.setData({defaultPickerValue: defIndex,showPicker: true});

    },
    //显示日历
    bindShowCalendar(e){
      let {field} = e.currentTarget.dataset;
      this.data.curtPickerField = field;
      let def = this.data.formData[field];
      this.setData({
        showCalendar: !this.data.showCalendar,
        defaultDatetimeValue: def
      })
    },
    //显示泥尾指定司机
    async bindShowDriver_old(e){

      let {index} = e.currentTarget.dataset,
        {items,destinationAssign,formData} = this.data,
        obj = {},
        first = items[0],
        second = first && first.child && first.child[0];
      obj.driverPickerValue = [first,second];
      this.setDriverLevel(3,first.id,second.id)
      obj.showDriver = true;
      obj.curtPickerIndex = index;  //记录当前泥尾索引

      let activeId = [],
        details = [];

      if (index === 'main'){
        details = this.data.driverDetail;
      } else {

        let destItem = destinationAssign[index];
        details = destItem.details || [];
        if (!details.length && destItem.row_id) {
          await this.getDestDriverDetl(destItem.row_id).then(res => {
            details = res;
            obj[`destinationAssign[${index}].details`] = res;
          })
        }
      }

      console.log(details);
      details.forEach(item =>{activeId.push(item.reference1_driver)})
      obj.activeId = [...activeId];  //显示当前泥尾已选司机

      this.setData(obj);
      this.isCheckedAll();
    },
    //显示泥尾指定司机
    async bindShowDriver(e){

      let {index} = e.currentTarget.dataset,
        {items,destinationAssign,formData} = this.data,
        obj = {}
        // first = items[0]
        // second = first && first.child && first.child[0];
      // obj.driverPickerValue = [first,second];
      // this.setDriverLevel(3,first.id,second.id)
      obj.showDriver = true;
      obj.curtPickerIndex = index;  //记录当前泥尾索引

      let activeId = [],
        details = [];

      if (index === 'main'){
        details = this.data.driverDetail;
        if (!details.length && this.data.row_id){
          await this.getAssignDriver().then(res =>{
            details = res;
          });
        }
      } else {

        let destItem = destinationAssign[index];
        details = destItem.details || [];
        if (!details.length && destItem.row_id) {
          await this.getDestDriverDetl(destItem.row_id).then(res => {
            details = res;
            obj[`destinationAssign[${index}].details`] = res;
          })
        }
      }

      details.forEach(item =>{activeId.push(item.reference1_driver)})
      obj.activeId = [...activeId];  //显示当前泥尾已选司机

      this.setData(obj);
      this.isCheckedAll();
    },
    //显示车队司机选择器
    bindShowDriverPicker(e){
      this.setData({showDriverPicker: true})
    },
    //收起车队司机选择器
    bindCloseDriverPicker(){
      this.setData({showDriverPicker: false})
    },
    //选择器确定显示司机
    bindConfirmDriverPicker(e){
      const { picker, value, index } = e.detail;
      this.setDriverLevel(3,value[0].id,value[1].id);
      this.setData({showDriverPicker: false,driverPickerValue: value})
    },
    //列表弹出
    async bindShow(e){
      let {type,index} = e.currentTarget.dataset,
        obj = {};
      if (type === 'delivery') {
        await this.getDelivery().then(() =>{
          obj.showDelivery = true;
        })
      }
      if (type === 'destination') {
        await this.getDestination().then(() =>{
          obj.showDestination = true;
        })
      }
      if (type === 'goods') {
        await this.getGoods().then(() =>{
          obj.showGoods = true;
        })
      }
      if (type === 'client') {
        await this.getClient().then(() =>{
          obj.showClient = true;
        })
      }
      if (type === 'destClient') {
        await this.getDestClient().then(() =>{
          obj.showDestClient = true;
        })
      }
      if (type === 'carTeam') obj.showDriverPicker = true;
      if (type === 'project') {
        await this.getProject().then(() =>{
          obj.showProject = true;
        })
      }

      if (type === 'location'){
        this.onChooseLocation();
      }

      if (type !== 'carTeam') obj.curtPickerIndex = index;



      this.setData(obj)
    },
    // 列表弹窗关闭
    bindClose(){
      this.setData({showDelivery: false,showDestination: false,showDriver: false,showGoods: false,showPicker: false,showClient: false,showDestClient: false,showProject: false})
    },
    //泥尾弹窗关闭
    bindCloseDest(){
      this.setData({showAddDest: false})
    },

    //确定选择
    bindSelectProject(e){
      let {item} = e.currentTarget.dataset;
      //231220 yan 增加选择项目映射带出工地、所属单位
      this.setData({
        ['formData.xiangmu']: item.row_id,
        ['formData.xiangmu;value']: item.xiangmumingchen,
        ['formData.reference1_all_delivery']: item.gongdi,
        ['formData.reference1_all_delivery;value']: item['gongdi;value'],
        ['formData.order_name']: item['gongdi;value'],
        ['formData.Order_client_ID']: item.wanglaidanwei,
        ['formData.Order_client_ID;value']: item['wanglaidanwei;value'],
        // ['formData.gongdilianxiren']: item.lianxiren,
        // ['formData.gongdilianxidianhua']: item.lianxidianhua,
        showProject: false
      })
      console.log(this.data.formData);
      // 231220 end

    },
    bindSelectDelivery(e){
      let {item} = e.currentTarget.dataset;
      //231220 yan 取消选择工地映射带出所属单位
      this.setData({
        ['formData.reference1_all_delivery']: item.row_id,
        ['formData.reference1_all_delivery;value']: item.delivery_name,
        ['formData.order_name']: item.delivery_name,
        // ['formData.Order_client_ID']: item.Order_client_ID,
        // ['formData.Order_client_Name']: item['Order_client_ID;value'],
        ['formData.gongdilianxiren']: item.lianxiren,
        ['formData.gongdilianxidianhua']: item.lianxidianhua,
        showDelivery: false
      })
      // 231220 end
    },
    bindSelectDestination(e){
      let {item} = e.currentTarget.dataset,
        {curtPickerIndex} = this.data;
      if (curtPickerIndex === 'main'){
        this.setData({
          ['formData.ZhiDingXieHuoDiZhiXiaoNaChang']: item.row_id,
          ['formData.ZhiDingXieHuoDiZhiXiaoNaChang;value']: item.destination_name,
          showDestination: false
        })
        return
      }
      this.setData({
        [`destinationAssign[${curtPickerIndex}].reference1_all_destination`]: item.row_id,
        [`destinationAssign[${curtPickerIndex}].reference1_all_destination;value`]: item.destination_name,
        [`destinationAssign[${curtPickerIndex}].Order_client_ID`]: item.Order_client_ID,
        [`destinationAssign[${curtPickerIndex}].Order_client_ID;value`]: item['Order_client_ID;value'],
        [`destinationAssign[${curtPickerIndex}].xiaonachanglianxiren`]: item.lianxiren,
        [`destinationAssign[${curtPickerIndex}].xiaonachanglianxidianhua`]: item.lianxidianhua,
        showDestination: false
      })

    },
    bindSelectGoods(e){
      let {item} = e.currentTarget.dataset,
        {curtPickerIndex} = this.data;
      this.setData({
        [`destinationAssign[${curtPickerIndex}].reference1_goods`]: item.row_id,
        [`destinationAssign[${curtPickerIndex}].reference1_goods;value`]: item.goods_name,
        showGoods: false
      })
    },
    bindSelectClient(e){
      let {item,index} = e.currentTarget.dataset,
        {curtPickerIndex} = this.data,
        obj = {showClient: false,showDestClient: false};
      if (curtPickerIndex === undefined){
        obj['formData.Order_client_ID'] = item.row_id;
        obj['formData.Order_client_ID;value'] = item.customer_name;
      } else {
        obj[`destinationAssign[${curtPickerIndex}].Order_client_ID`] = item.row_id;
        obj[`destinationAssign[${curtPickerIndex}].Order_client_ID;value`] = item.customer_name
      }
      this.setData(obj)
    },
    //指定司机变化
    confirmDriver_old(){
      let {destinationAssign,curtPickerIndex,activeId ,formData,} = this.data;
      /*if (curtPickerIndex === 'addDest'){
        this.setData({addDestDriver: activeId,showDriver: false})
        return
      }*/
      let add = [],del = [],
        rid = 0,
        table_id = '',
        parent_table_id = '',
        driverDetail = [];  //司机明细表

      if (curtPickerIndex === 'main') {
        driverDetail = this.data.driverDetail;
        rid = formData.row_id;
        parent_table_id = 'muck_order_main'
        table_id = 'muck_order_assign_personnel';
      }else {
        let destData = destinationAssign[curtPickerIndex]
        driverDetail = destData.details;
        rid = destData.row_id;
        parent_table_id = 'muck_order_assign_destination'
        table_id  = 'muck_order_assign_destination_personnel'
      }

      //主表指派司机，且新增
      if (curtPickerIndex === 'main' && !rid) {
        let add = [];
        activeId.forEach(item => { add.push({row_id: 0,reference1_driver: item}) });
        this.setData({
          showDriver: false,
          driverDetail: add
        })
        return
      }
      //明细表指派司机，且新增
      if (!rid){
        let add = [];
        activeId.forEach(item => { add.push({row_id: 0,reference1_driver: item}) });
        this.setData({
          showDriver: false,
          [`destinationAssign[${curtPickerIndex}].details`]: add
        })
        return
      }
      console.log(driverDetail);
      activeId.forEach(item => {
        let exit = driverDetail.find(ite => ite.reference1_driver == item);
        if (!exit)add.push({
          details: [],
          entity: {row_id: 0,reference1_driver: item}
        })
      });
      driverDetail.forEach(item => {
        let exit = activeId.find(ite => ite == item.reference1_driver);
        if (!exit) del.push(item.row_id);
      });

      wx.showLoading({mask: true});
      let pms = [];
      if (del.length){
        pms.push(this.delData(table_id,del.join(',')))
      }
      if (add.length){
        let details = [{
          table_id,
          entitys: add
        }];
        let post = {
          table: {
            table_id: parent_table_id,
            entitys: [
              {
                details,
                entity: {row_id: rid}
              }
            ]
          }
        }
        // console.log(post);
        pms.push(this.updateCustomData(post))
      }
      if (pms.length){
        Promise.all(pms).then(() => {
          wx.$toast('修改成功');
          this.setData({showDriver: false});
          wx.showLoading({mask: true});
          if (curtPickerIndex === 'main'){
            this.getDetailData().then(() => {
              wx.hideLoading()
            });
          }else {
            this.getDestDriverDetl(rid).then((res) => {
              this.setData({
                [`destinationAssign[${curtPickerIndex}].details`]: res
              });
              wx.hideLoading();
            });
          }
        })
      } else {
        wx.hideLoading();
        this.setData({showDriver: false})
      }
    },
    confirmDriver(e){
      let activeId = e.detail
      let {destinationAssign,curtPickerIndex ,formData,} = this.data;
      /*if (curtPickerIndex === 'addDest'){
        this.setData({addDestDriver: activeId,showDriver: false})
        return
      }*/
      let add = [],del = [],
        rid = 0,
        table_id = '',
        parent_table_id = '',
        driverDetail = [];  //司机明细表

      if (curtPickerIndex === 'main') {
        driverDetail = this.data.driverDetail;
        rid = formData.row_id;
        parent_table_id = 'muck_order_main'
        table_id = 'muck_order_assign_personnel';
      }else {
        let destData = destinationAssign[curtPickerIndex]
        driverDetail = destData.details;
        rid = destData.row_id;
        parent_table_id = 'muck_order_assign_destination'
        table_id  = 'muck_order_assign_destination_personnel'
      }

      //主表指派司机，且新增
      if (curtPickerIndex === 'main' && !rid) {
        let add = [];
        activeId.forEach(item => { add.push({row_id: 0,reference1_driver: item}) });
        this.setData({
          showDriver: false,
          driverDetail: add
        })
        return
      }
      //明细表指派司机，且新增
      if (!rid){
        let add = [];
        activeId.forEach(item => { add.push({row_id: 0,reference1_driver: item}) });
        this.setData({
          showDriver: false,
          [`destinationAssign[${curtPickerIndex}].details`]: add
        })
        return
      }
      console.log(driverDetail);
      activeId.forEach(item => {
        let exit = driverDetail.find(ite => ite.reference1_driver == item);
        if (!exit)add.push({
          details: [],
          entity: {row_id: 0,reference1_driver: item}
        })
      });
      driverDetail.forEach(item => {
        let exit = activeId.find(ite => ite == item.reference1_driver);
        if (!exit) del.push(item.row_id);
      });

      wx.showLoading({mask: true});
      let pms = [];
      if (del.length){
        pms.push(this.delData(table_id,del.join(',')))
      }
      if (add.length){
        let details = [{
          table_id,
          entitys: add
        }];
        let post = {
          table: {
            table_id: parent_table_id,
            entitys: [
              {
                details,
                entity: {row_id: rid}
              }
            ]
          }
        }
        // console.log(post);
        pms.push(this.updateCustomData(post))
      }
      if (pms.length){
        Promise.all(pms).then(() => {
          wx.$toast('修改成功');
          this.setData({showDriver: false});
          wx.showLoading({mask: true});
          if (curtPickerIndex === 'main'){

            this.getAssignDriver().then(() => {
              wx.hideLoading()
            });
           /* this.getDetailData().then(() => {
              wx.hideLoading()
            });*/
          }else {
            this.getDestDriverDetl(rid).then((res) => {
              this.setData({
                [`destinationAssign[${curtPickerIndex}].details`]: res
              });
              wx.hideLoading();
            });
          }
        })
      } else {
        wx.hideLoading();
        this.setData({showDriver: false})
      }
    },
    cancelDriver(){
      this.setData({showDriver: false})
    },
    //单选项变化
    bindRadioChange(e){
      let {type,index} = e.currentTarget.dataset,
        value = e.detail,obj = {};
     /* if (type === 'order'){
        this.data.formData.need_fill_order_no = value;
        this.data.formData.need_fill_excavator_no = value;
      }else if (type === 'img'){
        this.data.formData.need_fill_order_img = value;
        this.data.formData.need_fill_excavator_img = value;
      }else {
        this.data.formData[type] = value;
      }*/

      if (index >= 0){
        obj[`destinationAssign[${index}].${type}`] = value;
      } else {
        obj[`formData.${type}`] = value;
      }
      // this.data.formData[type] = value;
      this.setData(obj)
    },
    //确认选择选择器
    bindConfirmPicker(e){
      let {value} = e.detail,
        {curtPickerField,curtPickerIndex} = this.data,
        obj = {showPicker: false};
      // if (curtPickerField === 'construction_payment') {
      //   obj[`formData.${curtPickerField}`] = value;
      // }else {
      obj[`destinationAssign[${curtPickerIndex}].${curtPickerField}`] = value;
      // }
      this.setData(obj)

    },
    //日期时间选择
    bindSelectDatetime(e){
      let value = e.detail,
        {curtPickerField} = this.data;
      this.setData({
        [`formData.${curtPickerField}`]: value
      });
    },
    //输入框修改
    bindChangeInput(e){
      console.log(e);
      let {value} = e.detail,
        {field,index,type} = e.currentTarget.dataset,
        obj = {};
      if (type === 'num')value = value || 0;
      if (field === 'TuZhiWeiZhiLieBiao'){
        obj[`formData.XuYaoTianTuZhiWeiZhi`] = !!value;
      }
      if (index >= 0){
        obj[`destinationAssign[${index}].${field}`] = value;
      } else {
        obj[`formData.${field}`] = value;
      }
      this.setData(obj);
    },
    //新增泥尾
    addDestination(){
      let {destinationAssign,destinationDefData} = this.data,
        def = {...destinationDefData};
      destinationAssign.push(def);
      this.setData({destinationAssign,})
      // this.setData({toView: 'item' + destinationAssign.length - 1})
      // this.setData({toView: 'toview'})
    },
    //删除泥尾
    delDestination(e){
      let {destinationAssign} = this.data,
        {index} = e.currentTarget.dataset,
        destData = destinationAssign[index];
      if (destData.row_id){
        wx.showModal({
          title: '提示',
          content: '确定删除该泥尾？',
          success: (res) => {
            if(res.confirm) {
              wx.showLoading({mask: true});
              this.delData('muck_order_assign_destination',destData.row_id + '').then(res => {
                wx.$toast('删除成功！');
                destinationAssign.splice(index,1);
                this.setData({ destinationAssign})
              })
            }
          },
        })
      } else {
        destinationAssign.splice(index,1);
        this.setData({ destinationAssign})
      }
    },


    //搜索输入框变化
    searchChange(e){
      let {type} = e.currentTarget.dataset,
        {searchValue} = this.data;
      searchValue[type] = e.detail;
      this.setData({searchValue});
    },
    // 搜索
    bindSearch(e){
      let {type} = e.currentTarget.dataset,
        {searchValue} = this.data,
        val = searchValue[type] || '',
        obj = {
          delivery: {listName: 'deliveryList',fieldName: ['delivery_name','Order_client_ID;value']},
          destination: {listName: 'destinationList',fieldName: ['destination_name','Order_client_ID;value']},
          driver: {listName: 'crtDriver',fieldName: 'text'},
          goods: {listName: 'goodsList',fieldName: 'goods_name'},
          client: {listName: 'clientList',fieldName: 'customer_name'},
          destClient: {listName: 'destClientList',fieldName: 'customer_name'},
          project: {listName: 'projectList',fieldName: 'xiangmumingchen'},
        },
        {listName,fieldName} = obj[type],
        list = this.data[listName];
      list.forEach(item => {
        let text = item[fieldName];
        if (typeof fieldName === 'object'){
          text = [];
          fieldName.forEach(ite => {item[ite] && text.push(item[ite])});
          text = text.join('');
        }
        item.isHide = text && text.indexOf(val) < 0
      })
      this.setData({[listName]: list});
      if (type === 'driver') this.isCheckedAll(); //司机搜索，检查是否全选，勾起
    },

    //判断必填项 data:数据项，required必填项对象
    checkRequired(data,required){
      let flag = true;
      Object.keys(required).forEach(item => {
        let value = data[item]
        if (flag && ['',undefined,null].includes(value)){
          wx.$toast(required[item]);
          flag = false;
        }
      })
      return flag;
    },


    //选择司机
    onClickItem(e){
      const { activeId, } = this.data;
      let {id} = e.currentTarget.dataset;

      const index = activeId.indexOf(id);
      if (index > -1) {
        activeId.splice(index, 1);
      } else {
        activeId.push(id);
      }

      this.setData({ activeId });
      this.isCheckedAll();
    },
    //获取司机分级信息
    getDriverLevel(post){
      let url = 'ZTAuth/query_driver_inf_lv';
      return new Promise(resolve => {
        wx.showLoading({mask: true})
        wx.$post(5,url,post).then(res => {
          if (res.errcode != 0) return;
          wx.hideLoading()
          let data = res.data.row || [],
            arr = [],
            id = '',text = '',
            idName = '',textName = '';
          if (post.lv === 1){
            idName = 'r_suoshuchedui';textName = 'r_suoshuchedui_value';
            arr.push({
              text: '全部',
              id: 'all',
              children: []
            })
          }
          if (post.lv === 2){
            idName = 'suoshufendui';textName = 'suoshufendui_value';
            arr.push({
              text: '全部',
              id: 'all',
              children: []
            })
          }
          if (post.lv === 3){
            idName = 'row_id';textName = ['chelianghaoma','jiashiyuanxingming','suoshufendui_value'];
          }
          data.forEach(item => {
            let id = item[idName];
            if (!id) return;
            let text = '';
            if (typeof textName === 'object'){
              text = [];
              textName.forEach(ite => {
                if (ite === 'suoshufendui_value' && !item[ite]) {
                  item.r_suoshuchedui_value && text.push(item.r_suoshuchedui_value)
                }else {
                  item[ite] && text.push(item[ite])
                }
              });
              text = text.join('-');
            }else {
              text = item[textName] || '';
            }
            arr.push({
              text,
              id
            })
          });
          resolve(arr)
        })
      })
    },
    //设置显示车队司机
    setDriverLevel_old(lv,id,id2){
      let {firstActiveIndex,secondActiveIndex,items,isLoadDriverLevel} = this.data;
      //车队
      if (lv === 1){
        // if (isLoadDriverLevel) return
        this.getDriverLevel({lv: 1}).then(res =>{
          //231218 yan 增加车队选择器选项
          this.setData({items: res,[`carTeamColumns[0].values`]: res})
          this.data.isLoadDriverLevel = true
          //231218 end
          //默认加载下级分队
          if (res[0]){
            this.setDriverLevel(2,res[0].id,)
          }
        })
      }
      let first = items.filter(item => item.id === id)[0] //一级车队
      //分队
      if (lv === 2){
        let child = first && first.child;
        if (child){
          this.setData({[`carTeamColumns[1].values`]: child});
          return
        }
        let post = {lv: 2};
        post.lv_1_row_id = id === 'all' ? '' : id;
        this.getDriverLevel(post).then(res => {
          //231218 yan 增加车队选择器选项
          let item = items.filter(ite => ite.id === id)[0];
          item.child = res;
          // this.setData({[`items[${index}].child`]: res});
          this.setData({items,[`carTeamColumns[1].values`]: res});


          /*注释 不需要默认加载
          if (res[0]){
            this.setDriverLevel(3,id,res[0].id)
          }*/
          //231218 end
        })
      }
      //司机
      if (lv === 3){
        let second = first && first.child.filter(item =>  item.id === id2)[0] //二级车队
        let child = second.children || [];
        if (child.length){
          //清空搜索条件
          child.map(item => item.isHide = false);
          this.setData({crtDriver: child});
          this.isCheckedAll();//检查是否全选，勾起
          return
        }
        let post = {lv: 3};
        post.lv_1_row_id = id === 'all' ? '' : id;
        post.lv_2_row_id = id2 === 'all' ? '' : id2;
        this.getDriverLevel(post).then(res => {
          let item = items.filter(ite => ite.id === id)[0],
            child = item && item.child,
            item2 = child && child.filter(ite => ite.id === id2)[0];
          if (!item2) return;
          item2.children = res;
          item.child = child;
          // this.setData({[`items[${firstActiveIndex}].child[${index}].children`]: res});
          this.setData({items,crtDriver: res});
          this.isCheckedAll();  //检查是否全选，勾起
          // this.setData({items});
        })
      }
    },
    //全选司机
    checkAllDriver({detail}){
      let {items,firstActiveIndex,secondActiveIndex,activeId,driverPickerValue,crtDriver} = this.data;

      // 231219 yan 修改全选司机
      // let drivers = items[firstActiveIndex].child[secondActiveIndex].children;
      // drivers.forEach(item =>{
      crtDriver.forEach(item =>{
        if (item.isHide) return   //已隐藏的不全选
        let index = activeId.indexOf(item.id);
        if (detail && index < 0){
          activeId.push(item.id)
        }
        if (!detail && index >= 0){
          activeId.splice(index, 1);
        }
      })
      //231219 end

      this.setData({checkAll: detail,activeId});
    },
    //检车当前显示的司机是否已全选
    isCheckedAll(){
      const { activeId,crtDriver,items,firstActiveIndex,secondActiveIndex, } = this.data;
      /*let first = items[firstActiveIndex],
        second = first && first.child && first.child[secondActiveIndex],
        drivers = second && second.children;
      if (!drivers)return;*/
      let showAll = crtDriver.filter(item => !item.isHide),
        checkAll = showAll.every(item => activeId.includes(item.id));
      this.setData({ checkAll });
    },
    //车队选择器变化
    onColumnsChange(e){
      const { picker, value, index } = e.detail;
      let {items} = this.data,
        item = items[index],
        {child} = item;
      // let first = items.filter(item => item.id === value[0].id)[0] //一级车队
      //车队（一级）
      if (!index){
        this.setDriverLevel(2,value[0].id)
        /*let child = first.child;
        if (!child) {
          this.setDriverLevel(2,first.id)
        }else {
          this.setData({[`carTeamColumns[1].values`]: child});
        }*/
      }
      //分队（二级）
      else {
        /*let second = first.child.filter(item =>  item.id === value[1].id)[0] //二级车队
        let child = second.children;
        if (!child){
          this.setDriverLevel(3,first.id,second.id)
        }*/

        // this.setDriverLevel(3,value[0].id,value[1].id)

      }
      // picker.setColumnValues(1, citys[value[0]]);
    },
    //处理泥尾指定司机
    fmtDestDriverDetl(idArr){
      let arr = [];
      idArr && idArr.forEach(item =>{
        arr.push({
          details: [],
          entity: item
        })
      });
      return arr;
    },

    // 获取司机
    setDriverLevel(lv,id,id2){
      let {firstActiveIndex,secondActiveIndex,items} = this.data;
      //车队
      if (lv === 1){
        this.getDriverLevel({lv: 1}).then(res =>{
          this.setData({options: res})
        })
      }
      let first = items.filter(item => item.id === id)[0] //一级车队
      //分队
      if (lv === 2){
        let child = first && first.child;
        if (child){
          this.setData({[`carTeamColumns[1].values`]: child});
          return
        }
        let post = {lv: 2};
        post.lv_1_row_id = id === 'all' ? '' : id;
        this.getDriverLevel(post).then(res => {
          //231218 yan 增加车队选择器选项
          let item = items.filter(ite => ite.id === id)[0];
          item.child = res;
          // this.setData({[`items[${index}].child`]: res});
          this.setData({items,[`carTeamColumns[1].values`]: res});


          /*注释 不需要默认加载
          if (res[0]){
            this.setDriverLevel(3,id,res[0].id)
          }*/
          //231218 end
        })
      }
      //司机
      if (lv === 3){
        let second = first && first.child.filter(item =>  item.id === id2)[0] //二级车队
        let child = second.children || [];
        if (child.length){
          //清空搜索条件
          child.map(item => item.isHide = false);
          this.setData({crtDriver: child});
          this.isCheckedAll();//检查是否全选，勾起
          return
        }
        let post = {lv: 3};
        post.lv_1_row_id = id === 'all' ? '' : id;
        post.lv_2_row_id = id2 === 'all' ? '' : id2;
        this.getDriverLevel(post).then(res => {
          let item = items.filter(ite => ite.id === id)[0],
            child = item && item.child,
            item2 = child && child.filter(ite => ite.id === id2)[0];
          if (!item2) return;
          item2.children = res;
          item.child = child;
          // this.setData({[`items[${firstActiveIndex}].child[${index}].children`]: res});
          this.setData({items,crtDriver: res});
          this.isCheckedAll();  //检查是否全选，勾起
          // this.setData({items});
        })
      }
    },
    onChange(e) {
      console.log(e);
      const { value,tabIndex } = e.detail;
      if (tabIndex === 0){
        let post = {lv: 2};
        post.lv_1_row_id = value === 'all' ? '' : value;
        let index = this.data.options.findIndex(item => item.id == value);
        console.log(index);
        this.getDriverLevel(post).then(res => {
          this.setData({
            [`options[${index}].children`]: res,
          })
        })
      }
    },

    //获取泥尾司机明细表资料
    getDestDriverDetl_old(id){
      return new Promise(resolve => {
        wx.showLoading({mask: true})
        this.getCustomRow('muck_order_assign_destination',id).then(data =>{
          wx.hideLoading();
          if (data){
            let rowData = data.entity[0],
              {detail1,detail2} = data,
              driverDetail = [],destinationDetail = [];
            if (detail1.table_id === 'muck_order_assign_destination_personnel') {
              driverDetail = detail1.entity;
            }else {
              driverDetail = detail2.entity;
            }

            resolve(driverDetail);
            return
          }
          resolve([]);
        })
      })
    },
    getDestDriverDetl(id){
      return new Promise(resolve => {
        let where = [{CompareValue: id, CompareWith: "muck_order_assign_destination_personnel.parent_row_id", Operator: "=", or: 0}],
          fieldList = ['row_id','reference1_driver'];
        this.getCustomData('muck_order_assign_destination_personnel',where,fieldList.join(',')).then(data =>{
          this.setData({driverDetail: data || []})
          resolve(data || []);
        })
      })
    },

    // 250427 选择位置
    onChooseLocation(){
      let options = {},
        {rowData} = this.data;
      if (rowData){
        rowData.ZhiDingXieHuoJingDu && (options.longitude = rowData.ZhiDingXieHuoJingDu )
        rowData.ZhiDingXieHuoWeiDu && (options.latitude = rowData.ZhiDingXieHuoWeiDu )
      }
      wx.chooseLocation({
        ...options,
        success: (res) => {
          console.log(res);
          let { name, address, latitude, longitude, } = res
          this.setData({
            ['formData.ZhiDingXieHuoDiZhi']: name,
            ['formData.ZhiDingXieHuoJingDu']: longitude,
            ['formData.ZhiDingXieHuoWeiDu']: latitude,
          })
        },
        fail: (res) => {
          console.log(res);
          let { errMsg, } = res
          if(errMsg.indexOf('cancel') > -1) return
          wx.showModal({
            title: 'wx.chooseLocation fail',
            content: JSON.stringify(res),
            confirmText: '确定',
            success: (res) => {},
          })
        },
      })
    },

    //获取需要提交的数据 obj: 需要获取的数据项，data: 数据来源
    getSubmitData(data,obj,){
      let flag = true,responce = {};
      for(let key in obj){
        let value = data[key],
        reqiredMsg = obj[key];
        if (reqiredMsg && !value){
          flag = false;
          wx.$toast(reqiredMsg)
          break;
        }
        if (key === 'is_used'){
          value = true;
        }
        responce[key] = value
      }
      if (flag) return responce

    },


    initField(){
      let {auth,mainField,mainAuthField} = this.data;
      Object.keys(mainAuthField).forEach(item =>{
        let fieldObj = mainAuthField[item],
          authObj = auth.find(ite => ite.function_id === item)
        if (authObj && authObj.is_see) {
          fieldObj.label = authObj.function_name;
          mainField.push(fieldObj)
        }
      });
      this.setData({mainField})
    },

  //  获取权限列表
    getAuthorityList(fid, pid, rid){
      return new Promise((resolve, reject) => {
        let post = {
          user_id: wx.getStorageSync('user_id'),
          function_id: fid,
          pare_id: pid || '',
          row_id: rid,
        }
        wx.$post(4, 'QX/PRO_QX_list', post).then(res => {
          if(res.errcode !== 0) return
          res = res.data
          let list = res.row || [];
          resolve(list)
        })
      })
    }
  },
});
